package top.guoyang.springboot3.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Random;

public class EncryptorUtils {
    public static final String RAND_STR = "abcdefghijklmnopqrstuvwxyz";
    public static final Random RANDOM = new Random();


    /**
     * 生成随机字符串
     *
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String makeRandomStr(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {

            sb.append(RAND_STR.charAt(RANDOM.nextInt(RAND_STR.length())));
        }
        return sb.toString();
    }

    /**
     * 生成盐
     *
     * @return 盐
     */

    public static String makeSalt() {
        return makeRandomStr(5);
    }

    /**
     * md5加密
     *
     * @param str 待加密字符串
     * @return md5加密后的字符串
     */
    public static String md5(String str) {
        return StringUtils.hasText(str)
                ? DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8))
                : "";
    }

    /**
     * md5加盐加密
     *
     * @param str  待加密字符串
     * @param salt 盐
     * @return md5加盐加密后的字符串
     */
    public static String md5(String str, String salt) {
        String base = md5(str) + salt;
        return md5(base);

    }
}
